package com.geline.uploadfile;

import com.geline.uploadfile.dao.InitDDLRunner;
import com.geline.uploadfile.handler.UploadFileHandler;
import com.geline.uploadfile.job.DeleteFileJob;
import com.geline.uploadfile.pojo.JobUploadFile;
import com.geline.uploadfile.pojo.JobUploadFileProperties;
import com.geline.uploadfile.service.BaseUploadService;
import com.geline.uploadfile.service.LocalUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * 配置 - 删除垃圾文件定时任务
 * @author: mengxin
 * @date: 2022/11/6 17:54
 */
@EnableConfigurationProperties(value = JobUploadFileProperties.class)
public class JobUploadFileAutoConfiguration {

    @Autowired
    private JobUploadFileProperties properties;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private UploadFileHandler uploadFileHandler;

    @Bean
    @ConditionalOnMissingBean
    public BaseUploadService initBaseUploadService(){
        return new LocalUploadService(properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public JobUploadFileService initJobUploadFileService(BaseUploadService service){
        return new JobUploadFileService(properties, service);
    }

    @Bean
    @ConditionalOnMissingBean
    public DeleteFileJob initDeleteFileJob(){
        try {
            initTable();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DeleteFileJob job = new DeleteFileJob(properties, jdbcTemplate, uploadFileHandler);
        job.start();
        return job;
    }

    //初始化table
    protected void initTable() throws SQLException {
        List<JobUploadFile> list = properties.getList();
        String table = list.get(0).getTable();
        //启动时检查表是否存在，不存在直接生成一张表
        InitDDLRunner ddlRunner = new InitDDLRunner(jdbcTemplate.getDataSource(), table);
        ddlRunner.execute();
    }
}
